package com.qiyou.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qiyou.dao.IBlogDao;
import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.entity.Blog;

/**
 * 获取博客详细信息
 * 
 */
@WebServlet(name = "BlogList", urlPatterns = { "/BlogList" })
public class BlogListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		IBlogDao blogDao = DaoFactory.getBlogDao();
		List<Blog> blogs = null;

		String userId = request.getParameter("userId");
		String sort = request.getParameter("sort");

		try {
			if (null != userId) {
				blogs = blogDao.getBlogs(userId);
				if (null != blogs) {
					request.setAttribute("blogs", blogs);
					request.getRequestDispatcher("bloglist.jsp").forward(
							request, response);
					return;
				}
			}

			if ("date".equalsIgnoreCase(sort)) {
				String sql = "order by blogDate desc limit 25";
				blogs = null;
				blogs = blogDao.getBlogs(new Object[] { sql });

				if (null != blogs) {
					request.setAttribute("blogs", blogs);
					request.getRequestDispatcher("bloglist.jsp").forward(
							request, response);
					return;
				}
			}

			if ("num".equalsIgnoreCase(sort)) {
				String sql = "order by blogNums desc limit 25";
				blogs = null;
				blogs = blogDao.getBlogs(new Object[] { sql });

				if (null != blogs) {
					request.setAttribute("blogs", blogs);
					request.getRequestDispatcher("bloglist.jsp").forward(
							request, response);
					return;
				}
			}
		} catch (Exception e) {

		}
		response.getWriter().print("<script type='text/javascript'>alert('您的请求有误!');history.go(-1);</script>");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
